import { ref } from 'vue'
import {userService} from '@/api/userProxy'
import {ResponseError} from '@/utils/request'
import { AuthToken } from '@/utils/token-util'


const token = ref('')
const name = ref('')
const avatar = ref('')
const role = ref(-1)

export const UserStore = () => {
  const doLogin = async (username: string, password: string) => {
    userService.login(username, password).then((response:any) => {
      let resData:any = response.data;
      if (resData.code === 0) {
        token.value = resData.data
        AuthToken.setToken(resData.data)
      } else {
        throw Error(resData.message)
      }
    }).catch((ex:any) => {
      let respErr = ex as ResponseError;
      console.log(respErr);
      throw respErr.error;
    });
  }

  const getUserInfo = async () => {
    userService.getInfo().then((response:any) => {
      let resData:any = response.data;
      const user : any  = resData.data;
      if (user) {
        name.value = user.name
        avatar.value = user.avatar
        role.value = user.role
      } else {
        throw Error('没有获取到登陆信息')
      }
    }).catch((ex:any) => {
      let respErr = ex as ResponseError;
      console.log(respErr);
      throw respErr.error;
    });
  }

  const resetToken = () => {
    token.value = ''
    AuthToken.removeToken()
  }

  const doLogout = async () => {
    await userService.logout()
    resetToken()
  }

  return {
    token,
    name,
    avatar,
    role,
    doLogin,
    getUserInfo,
    resetToken,
    doLogout,
  }
}
